package com.qeng.aiwanba.fragment;

import android.app.Fragment;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;

import com.github.lzyzsd.jsbridge.BridgeWebView;
import com.github.lzyzsd.jsbridge.DefaultHandler;
import com.qeng.aiwanba.R;
import com.qeng.aiwanba.util.Constants;
import com.qeng.aiwanba.util.LocalHtmlUtil;
import com.qeng.aiwanba.util.MyBridgeUtil;
import com.qeng.aiwanba.util.MyWebViewClient;
import com.qeng.aiwanba.util.Util;
import com.tencent.smtt.export.external.interfaces.WebResourceError;
import com.tencent.smtt.export.external.interfaces.WebResourceRequest;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebView;

import static com.qeng.aiwanba.util.Constants.BROADCAST_HTML_DOWNLOAD_FINISH;

/**
 * Created by lixy on 2017/9/22.
 */

public class BaseFragment extends Fragment {
    private Context context;
    private View root;
    private FrameLayout framelayout;
    private LinearLayout network_error_ll;

    private BridgeWebView webView;
    private MyWebViewClient webViewClient;

    private MyBroadcastReceiver broadcastReceiver;
    private IntentFilter intentFilter;

//    private String url;
    private String urlIndex;

    public static BaseFragment newInstance(String url){
        BaseFragment fragment = new BaseFragment();
        Bundle bundle = new Bundle();
        bundle.putString("url", url);
        //fragment保存参数，传入一个Bundle对象
        fragment.setArguments(bundle);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if(root == null){
            context = getActivity();
            root = LayoutInflater.from(context).inflate(R.layout.fragment_main, null);

            initViews();

            registerBroadcast();

            urlIndex = getArguments().getString("url");
            webView.loadUrl(getUrl(urlIndex));
        }else{
            ViewGroup parent = (ViewGroup) root.getParent();
            if (null != parent) {
                parent.removeView(root);
            }
        }
        return root;
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        Log.e("tag","onHiddenChanged:"+hidden+" url:"+urlIndex);
        if(!hidden){
            noticeJsPageAppear();
//            webView.onResume();
//            webView.resumeTimers();
        }else{
//            webView.onPause();
//            webView.pauseTimers();
        }
        super.onHiddenChanged(hidden);
    }

    private String getUrl(String index){
        if(index.startsWith("http")){
            return index;
        }
        if(Constants.isLoadHtml) {
            return LocalHtmlUtil.getLocalHtml(context) + index;
        }else{
            return Constants.htmlIp+index;
        }
    }

    private void initViews(){
        framelayout = (FrameLayout)root.findViewById(R.id.framelayout);
        webView = (BridgeWebView) root.findViewById(R.id.webview);
        network_error_ll = (LinearLayout) root.findViewById(R.id.network_error_ll);
//        webView = new BridgeWebView(context);
//        framelayout.addView(webView,new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));

        settingWebview();

        if(!Util.isNetworkAvailable(context)){
            network_error_ll.setVisibility(View.VISIBLE);
        }else{
            network_error_ll.setVisibility(View.GONE);
        }
    }

    private void settingWebview(){

        webViewClient = new MyWebViewClient(webView) {
            @Override
            public boolean shouldOverrideUrlLoading(final WebView view, String url) {
                return super.shouldOverrideUrlLoading(view, url);
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
            }

            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                super.onReceivedError(view, request, error);
            }
        };

        webView.setDefaultHandler(new DefaultHandler());
        webView.setWebViewClient(webViewClient);
        webView.setWebChromeClient(new WebChromeClient());
        MyBridgeUtil.registerHandler(webView);

    }

    private void registerBroadcast(){
        intentFilter = new IntentFilter();
        intentFilter.addAction(Constants.BROADCAST_HTML_DOWNLOAD_FINISH);
        intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        broadcastReceiver = new MyBroadcastReceiver();
        context.registerReceiver(broadcastReceiver,intentFilter);
    }


    public void noticeJsKeyBack(){
        webView.callHandler("JSABackPageButtonClick",null,null);
    }

    public void noticeJsPageAppear(){
        webView.callHandler("JSAPageAppear",null,null);
    }

    public void noticeMainTab(int index){
        webView.callHandler("JSAPageButton",String.valueOf(index),null);
    }

    public void noticeOnlinePlayEnd(String result){
        webView.callHandler("JSAOnlinePlayFinish",result,null);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        context.unregisterReceiver(broadcastReceiver);
//        if(webView != null){
//            webView.clearHistory();
//            webView.clearCache(true);
//            webView.loadUrl("about:blank"); // clearView() should be changed to loadUrl("about:blank"), since clearView() is deprecated now
//            webView.freeMemory();
//            webView.pauseTimers();
//            webView = null;
//        }
    }

    private class MyBroadcastReceiver extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent.getAction().equals(BROADCAST_HTML_DOWNLOAD_FINISH)){
                webView.loadUrl(getUrl(urlIndex));
            }else if(intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)){
                if(Util.isNetworkAvailable(context)) {
                    webView.reload();
                    network_error_ll.setVisibility(View.GONE);
                }
            }
        }
    }
}
